#coding=utf8
import sys, MangaBase, re, urllib2, urlparse
import cmrhelper
class Parser(MangaBase.CMangaBase):
    "zxmh.net parser"
    def Start(self):
        self.IniRe()
        try:
            self.chaptercontent = urllib2.urlopen(self.m_url).read()
        except:
            self.m_mangalog.writeLog('get page content fail','fatal')
            return
        # if m_manganame is None,then parse manganame
        if not self.m_manganame:
            self.ParseName()
        self.GetChapters()
        if self.m_chapterlist:
            for item in self.m_chapterlist:
                self.ParseChapter(item[0], item[1])
        self.End()

    def IniRe(self):        
        self.namere = re.compile("<DIV class=center_title> (.*?)</DIV>")
        self.chapterre = re.compile(r'<li><a title=\'.*?\' href=\'(.*?)\' target=\'_blank\' >(.*?)</a></li>')
        self.picre = re.compile(r'var pic_path = \'(.*?)\';')
        self.pagere = re.compile(r'(datas\[\d+?\] = \'.*?\');')


    def ParseName(self):
        "get manga name if name is None"
        self.m_mangalog.writeLog('get manga name')
        if self.namere.findall(self.chaptercontent):
            self.m_manganame = self.namere.findall(self.chaptercontent)[0].decode('gbk').encode('utf-8')
            self.m_mangalog.writeLog('get manga name success, manga name [%s]' %
                                     self.m_manganame)

    def ParseChapter(self, curl, title):
        "parse each chapter to generate url of pictures"
        try:
            content = urllib2.urlopen(curl).read()
            datas = ['']*500
            pic_path = ''
            piclist = []
            if content:
                pic_path = self.picre.findall(content)[0]
                for item in self.pagere.findall(content):
                    exec(item)
                for item in datas:
                    if len(item) > 0:
                        turl = urlparse.urljoin(pic_path,item)
                        piclist.append([turl,turl,title])
                        self.PushPic([turl, turl,\
                                          title.decode('gbk').encode('utf-8'),\
                                          self.m_manganame])
        except  Exception, e:
            self.m_mangalog.writeLog(str(e) + ' in ParseChapter', 'error')
    
    def GetChapters(self):
        "get manga chapters"
        try:
            if self.chapterre.findall(self.chaptercontent):
                for item in self.chapterre.findall(self.chaptercontent):
                    title = item[1].decode('gbk').encode('utf-8')
                    self.m_chapterlist.append([urlparse.urljoin(self.m_url,item[0]),title])
                    self.m_chaptercnt += 1
            self.m_mangalog.writeLog('get chapters finish total: [%d] chapters'\
                                         % self.m_chaptercnt)
        except  Exception, e:
            self.m_mangalog.writeLog(str(e)+' in getchapter','error')

    def getpagenum(self, content):
        "get the chapters pagenum"
        '''第(1/17)页 跳转到第'''
        s = r"第\(1/(\d*?)\)页 跳转到第"
        s = s.decode('utf-8').encode('gbk')
        numre = re.compile(s)
        if numre.findall(content):
            return int(numre.findall(content)[0])
        else:
            return 0

    def pagegenerate(self, url,content,pagenum):
        pageurl = []
        pageurl.append(url)
        if pagenum:
            urlhead = url[0:-2]
            urltail = '/'
            for i in range(2,pagenum):
                pageurl.append(urlhead+str(i)+urltail)
        return pageurl

    def parserpic(self, attrs):
        result = self.picre.findall(attrs)
        if result:
            return result[0]
        else:
            return None
